package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 菜品添加
     */
    @CacheEvict(cacheNames = "dishdate:categoryid", allEntries = true)
    @PostMapping
    public R save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        return R.success("添加成功");
    }

    /**
     * 菜品分页查询
     */
    @GetMapping("page")
    public R page(Integer page, Integer pageSize, String name) {
        //dish菜品分页器
        Page<Dish> pageInfo1 = new Page<>(page, pageSize);

        //查询条件,排名从低到高
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.orderByAsc("sort").orderByDesc("update_time");
        //调用方法
        dishService.page(pageInfo1, queryWrapper);

        //创建dishdto分页对象
        Page<DishDto> pageInfo2 = new Page<>();

        //拷贝基本数据
        BeanUtils.copyProperties(pageInfo1, pageInfo2, "records");

        //拷贝records数据
        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : pageInfo1.getRecords()) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            //根据id查询菜品分类名称
            Category category = categoryService.getById(dish.getCategoryId());
            dishDto.setCategoryName(category.getName());
            dishDtoList.add(dishDto);
        }
        pageInfo2.setRecords(dishDtoList);
        return R.success(pageInfo2);
    }

    /**
     * 修改菜品
     */

    //1.修改之前要先回显数据,通过id查询
    @GetMapping("{id}")
    public R getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWishFlavor(id);
        return R.success(dishDto);
    }

    //2.修改数据
    @CacheEvict(cacheNames = "dishdate:categoryid", allEntries = true)
    @PutMapping
    public R update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);

        //清理所有菜品的缓存数据
        //获取所有以dishdate:categoryid:开头的key
        Set keys = redisTemplate.keys("dishdate:categoryid:*");
        //删除这些key
        redisTemplate.delete(keys);

        return R.success("添加成功");
    }

    /**
     * 通过id或者id数组删除菜品
     */
    @CacheEvict(cacheNames = "dishdate:categoryid", allEntries = true)
    @DeleteMapping
    public R deleteById(@RequestParam List<Long> ids) {
        dishService.removeWithFlavorByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 通过id或者id修改停售出售状态
     */
    @CacheEvict(cacheNames = "dishdate:categoryid", allEntries = true)
    @PostMapping("status/{status}")
    public R updateByIds(@PathVariable Integer status, @RequestParam List<Long> ids) {
        Dish dish = new Dish();
        dish.setStatus(status);
        for (Long id : ids) {
            dish.setId(id);
            dishService.updateById(dish);
        }
        return R.success("修改成功");
    }

    /**
     * 通过分类ID查询菜品
     */
    @Cacheable(value = "dishdate:categoryid",
            key = "#categoryId +" + "':'+#status",
            unless = "#result.data.size() == 0")
    @GetMapping("list")
    public R<List<DishDto>> list(Long categoryId, String name, Integer status) {

        //动态构造key
        /*String redisKey = "dishdate:categoryid:" + categoryId;
        //先从redis中获取缓存数据
        List<DishDto> dishDate = (List<DishDto>) redisTemplate.opsForValue().get(redisKey);
        if (dishDate != null) {
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDate);
        }*/

        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        dishQueryWrapper.eq(categoryId != null, "category_id", categoryId)
                        .eq(status != null, "status", status)
                        .like(StringUtils.isNotBlank(name), "name", name);
        List<Dish> dishList = dishService.list(dishQueryWrapper);
        //创建dishdto集合
        List<DishDto> dishDtoList = new ArrayList<>();
        //遍历dishlist集合
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            //拷贝第一份dishList数据
            BeanUtils.copyProperties(dish, dishDto);
            //拷贝第二份数据,口味集合,通过菜品Id查询口味集合
            LambdaQueryWrapper<DishFlavor> eq = Wrappers.lambdaQuery(DishFlavor.class)
                    .eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(eq);
            dishDto.setFlavors(dishFlavorList);
            dishDtoList.add(dishDto);
        }

       /* //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(redisKey, dishDtoList);*/

        return R.success(dishDtoList);
    }

}